#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <pwd.h>

#include "data.h"
#include "sqlink.h"
extern ENV_VAR* pENV_TABLE;

int do_help (int argc,char **argv);
int do_quit (int argc,char **argv);
int do_env  (int argc,char **argv);

int do_listcreate(int,char **);
int do_listprint(int,char **);
int do_listinsert(int,char **);

struct command k_cmd[KMAXSIZE] = {
    {"help",do_help,0,NULL},
    {"env",do_env,0,NULL},
    {"quit",do_quit,0,NULL},


    /*
     * sqlink operation
     * */
    {"sqcreate",do_listcreate,0,NULL},
    {"insert",do_listinsert,0,NULL},
    {"printlist",do_listprint,0,NULL},

    {"",NULL,0,NULL}
};

sqlist L=NULL;

int do_listcreate(int argc,char **argv) {
    L=create();
    return 0;
}
int do_listprint(int argc,char **argv) {
    printlist(L);
    return 0;
}
int do_listinsert(int argc,char **argv) {
    insert(L,0,L->length);
    return 0;
}

int do_env (int argc,char **argv)
{
    ENV_VAR* pvar=pENV_TABLE;
    /*
     * check ENV_TABLE's head infomation.
     * */
    if (*(int *)pvar->name != ENV_HEAD || *(int *)pvar->value != ENV_HEAD) {
        printf("ENV_VAR list have error\n");
        printf("pvar->name=%s",pvar->name);
        printf("pvar->value=%s",pvar->value);
        exit(1);
    }
    pvar=pvar->next;

    while(pvar != NULL) {
        if (strlen(pvar->name)<1 && strlen(pvar->value)<1) {
            continue;
        }
        printf("%s=%s\n",pvar->name,pvar->value);

        pvar=pvar->next;
    }
    return 0;
}

static void printcmdlist() {
    struct command *cmd=k_cmd;
    while(cmd->cmd) {
        printf("%s\n",cmd->name);
        cmd++;
    }

}
int do_help (int argc,char **argv)
{
    printf("Hello,world\n");
    printf("Be supported command:\n");
    printcmdlist();
    return 0;
}

int do_quit(int argc,char **argv)
{
    struct passwd *p;
    setpwent();
    p=getpwent();
    while (p->pw_uid!=getuid()) p=getpwent();
    printf("Bye!,%s\n",p->pw_name);
    endpwent();
    exit(1);
}
